import throttle from 'lodash/throttle';
import { browseFile, ExtractFileByAutoView } from '/@/api/demo/document';
import { Base64 } from 'js-base64';
import { GetResourceList } from '/@/api/demo/dict';
import { useMessage } from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();

// 统一的浏览方法
export const handleBrowseFile = throttle(async (record: Recordable, type: string) => {
  try {
    if (record.previewMethod == null) {
      createMessage.error('请先设置预览方式');
      return;
    }

    const res = await GetResourceList({ TypeName: '预览方式' });
    const name = res.find((item) => item.id === record.previewMethod)?.resourceName;

    if (!name) {
      createMessage.error('未找到匹配的预览方式');
      return;
    }

    // 通用提取 ID 和版本号
    let id: string | undefined;
    let version: number | undefined;

    if (type === '图文档工作区' || type === '新建流程') {
      id = record.oId;
      version = record.version;
    } else if (type === '发布区') {
      id = record.oid;
      version = record.docVersion;
    } else if (type === '知识库') {
      id = record.oId;
      version = record.curreVision;
    } else if (type === '待办流程') {
      id = record.oid;
      version = record.version;
    } else if (type === '零件附件') {
      id = record.fileId;
      version = record.fileVersion;
    } else if (type === '零件关联') {
      id = record.oId;
      version = record.version;
    } else if (type === '工艺文件') {
      id = record.oId;
      version = record.version;
    }

    if (!id || version == null) {
      createMessage.error('文件 ID 或版本号缺失');
      return;
    }

    if (name === 'kkFile') {
      const [url, host] = await browseFile(id, version);
      window.open(`${host}:8012/onlinePreview?url=${encodeURIComponent(Base64.encode(url))}`);
    } else if (name === 'autoVue') {
      const [url, host] = await ExtractFileByAutoView(id, version);
      window.open(
        `${host}:5098/AutoVue/OpenApplet.html?browse=${encodeURIComponent(Base64.encode(url))}`,
      );
    } else {
      createMessage.warning(`暂不支持的预览方式：${name}`);
    }
  } catch (error) {
    console.error('文件预览失败:', error);
    createMessage.error('文件预览失败，请稍后重试');
  }
}, 3000);
